<style lang="less" >
@import "../../personInfo.less";
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
@import "../../../styles/table-common.less";
.ivu-card-head {
  background: #378CFE;
  padding: 15px !important;

  .head-name {
    color: #fff;
  }

  .ivu-dropdown {
    a {
      color: #fff;
    }

    .light-text {
      color: #378CFE;
      border: none !important;
    }
  }
}
</style>

<style lang="less" scoped >
.wrapper01 {
  background: #fff; 
  max-width: 400px !important; 
  // flex: 0 0 220px;
  // width: 220px !important;
}

.cml5 {
  margin-left:5px
}

.c-drawer01 {
  /deep/ .ivu-drawer {
        width:500px !important;
    }
}
.c-drawer02 {
    /deep/ .ivu-drawer {
        width:1000px !important;
    }
    
}
.cmr10 {
  margin-right: 10px
}

</style>
<template>
  <div class="search">
    <Row :gutter="16" class="all-height">
      <Col span="18" class="all-height" style="display: flex;">
        <Card class="all-height card-child-height">
          <Sider  hide-trigger v-show="showType == 'tree'" class="wrapper01" :style="{'width': siderWidth}" >
            <Menu
                :active-name="activeName"
                theme="light"
                width="auto"
                @on-select="activeName=$event"
            >
              <MenuItem v-for="item in treeData" :key="item.value" :name="item.value" @click.native="selectTreeLevel(item)">{{ item.title }}</MenuItem>
            </Menu>
            <Spin size="large" fix v-if="treeLevelLoading"></Spin>
          </Sider>
        </Card>
        <Card class="all-height card-child-height" style="flex-grow: 1;">
          <Row class="operation">
            <Button v-has="'add'" @click="add" type="primary" icon="md-add" v-show="showType == 'tree' && this.form.level != '2'">
              添加子节点
            </Button>
            <Button v-has="'add1'" @click="addRoot" icon="md-add">添加一级节点</Button>
            <Button v-has="'delete'" @click="delAll" icon="md-trash">批量删除</Button>
            <Button v-has="'input'" @click="dropImportData">导入去向代码信息</Button>
            <Button @click="getParentList" icon="md-refresh">刷新</Button>
            <i-switch v-model="strict" size="large" class="cml5" v-show="showType == 'tree'">
              <span slot="open">级联</span>
              <span slot="close">单选</span>
            </i-switch>
          </Row>
          <Row>
            <Alert show-icon style="width: 80%">
              当前选择编辑：
              <span class="select-title">{{ editTitle }}</span>
              <a class="select-clear" v-show="form.id && editTitle" @click="cancelEdit">取消选择</a>
            </Alert>
            <Input
                v-model="searchKey"
                suffix="ios-search"
                @on-change="search"
                @on-select-change="selectTree"
                placeholder="输入名称搜索"
                style="width: 80%"
                clearable
            />
          </Row>
          <Row class="calc-px-height">
            <div style="position: relative; width: 100%;">
              <div class="tree-bar" :style="{maxHeight: maxHeight}">
                <Tree
                    ref="tree"
                    :data="data"
                    :load-data="loadData"
                    show-checkbox
                    @on-check-change="changeSelect"
                    @on-select-change="selectTree"
                    :check-strictly="!strict"
                ></Tree>
              </div>
              <Spin size="large" fix v-if="loading"></Spin>
            </div>
          </Row>
        </Card>
      </Col>
      <Col span="6" class="all-height" >
        <Card class="all-height card-child-height ">
          <Form ref="form" :model="form" :rules="formValidate" :label-width="labelWidth110" label-position="right">
            <FormItem label="上级去向代码" prop="parentCode">
              <Input v-model="form.parentCode" clearable disabled/>
            </FormItem>
            <FormItem label="上级去向" prop="parentTitle">
              <div style="display:flex;width:100%">
                <Input v-model="form.parentTitle" readonly disabled/>
              </div>
            </FormItem>
            <FormItem :label="getLabelCode" prop="profCode">
              <Input v-model="form.profCode" clearable/>
            </FormItem>
            <FormItem :label="getLabelName" prop="title">
              <Input v-model="form.title" clearable/>
            </FormItem>
            <FormItem label="排序值" prop="sortOrder" class="block-tool">
              <Tooltip trigger="hover" placement="right" content="值越小越靠前，支持小数">
                <InputNumber :max="1000" :min="0" v-model="form.sortOrder" style="width:100%"></InputNumber>
              </Tooltip>
            </FormItem>
            <FormItem class="br">
              <Button
                  v-has="'edit'"
                  @click="submitEdit"
                  :loading="submitLoading"
                  :disabled="!form.id || !editTitle"
                  type="primary"
                  icon="ios-create-outline"
              >修改
              </Button>
              <Button v-has="'clear'" @click="handleReset">重置</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>

    <!--添加子节点-->
    <Drawer  :title="modalTitle" v-model="modalVisible" draggable :mask-closable="false" class="c-drawer01">
      <div :style="{ maxHeight: maxDrawerHeight }" class="drawer-content ">
        <Form ref="formAdd" :model="formAdd" :rules="formValidate" label-position="top">
          <div v-if="showParent">
            <FormItem label="上级节点：" prop="parentTitle">
              {{ form.title }}
            </FormItem>
            <FormItem label="上级节点代码：" prop="parentCode">
              {{ form.profCode }}
            </FormItem>
          </div>
          <FormItem :label="getLabelChildCode" prop="profCode">
            <Input v-model="formAdd.profCode" clearable/>
          </FormItem>
          <FormItem :label="getLabelChildName" prop="title">
            <Input v-model="formAdd.title" clearable/>
          </FormItem>
          <FormItem label="排序值" prop="sortOrder" class="block-tool">
            <Tooltip trigger="hover" placement="right" content="值越小越靠前，支持小数">
              <InputNumber :max="1000" :min="0" v-model="formAdd.sortOrder" style="width:100%"></InputNumber>
            </Tooltip>
          </FormItem>
        </Form>
      </div>
      <div class="drawer-footer br">
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
        <Button @click="modalVisible = false">取消</Button>
      </div>
    </Drawer>
    <Drawer title="导入数据" closable v-model="importModalVisible" class="c-drawer02" >
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
          <Button
              :loading="reading"
              icon="ios-cloud-upload-outline"
              class="cmr10"
          >上传Excel文件
          </Button
          >
          <span v-if="uploadfile.name"
          >当前选择文件：{{ uploadfile.name }}</span
          >
        </Upload>
        <Button @click="clearImportData" icon="md-trash">清空数据</Button>
      </div>
      <Alert type="warning" show-icon
      >导入前请下载查看导入模版数据文件查看所需字段及说明，确保数据格式正确，不得修改列英文名称
      </Alert
      >
      <Table
          :columns="importColumns"
          border
          :height="height"
          :data="importTableData"
          ref="importTable"
      ></Table>
      <div class="drawer-footer">
        <Button @click="downloadTemple" type="info">下载导入模板</Button>
        <div style="position: absolute; right: 15px; display: inline-block">
          <Button @click="importModalVisible = false">关闭</Button>
          <Button
              :loading="importLoading"
              :disabled="importTableData.length <= 0"
              @click="importData"
              style="margin-left: 8px"
              type="primary"
          >
            确认导入
            <span v-if="importTableData.length > 0"
            >{{ importTableData.length }} 条数据</span
            >
          </Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>

<script>
import excel from "@/libs/excel";
import {getDictData, getDictDataByType} from "@/api";

export default {
  name: "professionalCode",
  components: {},
  data() {
    return {
      labelWidth110: 110,
      siderWidth: 200,
      currVersion: '2023',
      versionList: [],
      treeLevelLoading: false, // 树加载状态
      showType: "tree",
      maxDrawerHeight: 510,
      maxHeight: "500px",
      strict: true,
      gradNowDict: '0',
      editLevelTitle: '',// 编辑学历层次节点名称
      loading: false, // 树加载状态
      loadingEdit: false, // 编辑上级树加载状态
      modalVisible: false, // 添加显示
      selectList: [], // 多选数据
      selectLevelList: [], //学历层次多选数据
      showParent: false, // 显示上级标识
      modalTitle: "", // 添加标题
      editTitle: "", // 编辑节点名称
      searchKey: "", // 搜索树
      form: {
        // 编辑对象初始化数据
        id: "",
        title: "",
        parentId: "",
        parentTitle: "",
        sortOrder: 0,
        profCode: "",
        parentCode: "",
        dictMatch: "",
        dueTime: "",
        isParent: "",
      },
      formAdd: {
        // 添加对象初始化数据
      },
      formValidate: {
        // 表单验证规则
        sortOrder: [
          {
            required: true,
            type: "number",
            message: "排序值不能为空",
            trigger: "change"
          }
        ],
      },
      submitLoading: false,
      data: [],
      dataEdit: [],
      columns:[],
      columns_1: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          type: "index",
          title:"序号",
          width: 60,
          align: "center",
        },
        {
          title: "名称",
          key: "title",
          minWidth: 120,
          sortable: true,
          tree: true,
        },
        {
          title: "去向代码",
          key: "profCode",
          minWidth: 120,
          sortable: true,
        },
        {
          title: "排序",
          key: "sortOrder",
          width: 150,
          sortable: true,
          align: "center",
          sortType: "asc",
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          width: 200,
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                  "a",
                  {
                    on: {
                      click: () => {
                        this.tableAdd(params.row);
                      },
                    },
                  },
                  "添加子节点"
              ),
              h("Divider", {
                props: {
                  type: "vertical",
                },
              }),
              h(
                  "a",
                  {
                    on: {
                      click: () => {
                        this.remove(params.row);
                      },
                    },
                  },
                  "删除"
              ),
            ]);
          },
        },
      ],
      treeData: [], // 树数据
      importModalVisible: false,
      reading: false,
      importTableData: [],
      importColumns: [],
      exportModalVisible: false,
      uploadfile: {
        name: "",
      },
      importLoading: false,
      height: 510,
      activeName: "0",
    };
  },
  methods: {
    async init() {
      // 计算高度
      let height = document.documentElement.clientHeight;
      this.maxHeight = Number(height - 287) + "px";
      this.maxDrawerHeight = Number(height - 121) + "px";

      // 初始化一级节点
      this.getParentList();

      // 初始化一级节点为编辑上级节点使用
      this.getParentListEdit();
      // 后台获取版本列表
      await this.getVersionListInit();
    },
    async getAllDict() {
      this.treeLevelLoading = true;
      // let res = await this.postRequest("/dictData/getByTypePost", {type: "eduLevelType", version: this.currVersion})

      getDictDataByType("qx").then(res => {
        this.treeLevelLoading = false;
        if (res.success) {
          this.treeData = res.result;
        }else {
          this.treeData = null
        }
      })
    },
    selectTreeLevel(v) {
      if (v) {
        let str = JSON.stringify(v);
        let data = JSON.parse(str);
        this.activeName=data.value
        // this.treeDictData = data
        this.editLevelTitle = data.title;
        this.gradNowDict = data.value;  // 当前选择的去向层次字典值
        this.getParentList();
      } else {
        this.cancelEdit();
      }
    },
    getParentList() {
      this.loading = true;
      this.postRequest("/gqQxCode/getByParentCode", {
        parentCode: 0,
        dictValue: this.gradNowDict,
        version: this.currVersion
      }).then(res => {
        this.loading = false;
        if (res.success) {
          res.result.forEach(function (e) {
            e.title = e.profCode + '-' + e.title
            if (e.isParent) {
              e.loading = false;
              e.children = [];
              e._loading = false;
            }
          });
          this.data = res.result;
        }
      });
    },
    getParentListEdit() {
      // this.loadingEdit = true;
      // this.postRequest("/tree/getByParentId",{parentId:0}).then(res => {
      //   this.loadingEdit = false;
      //   if (res.success) {
      //     res.result.forEach(function(e) {
      //       if (e.isParent) {
      //         e.loading = false;
      //         e.children = [];
      //       }
      //     });
      //     // 头部加入一级
      //     let first = {
      //       id: "0",
      //       title: "一级节点"
      //     };
      //     res.result.unshift(first);
      //     this.dataEdit = res.result;
      //   }
      // });
      // 模拟请求成功
      this.dataEdit = [];
    },
    loadData(item, callback) {
      // 异步加载树子节点数据
      this.postRequest("/gqQxCode/getByParentCode ", {
        parentCode: item.profCode,
        dictValue: item.dictMatch,
        version: '2023'
      }).then(res => {
        if (res.success) {
          res.result.forEach(function (e) {
            e.title = e.profCode + '-' + e.title
            if (e.isParent) {
              e.loading = false;
              e.children = [];
              e._loading = false;
            }
          });
          callback(res.result);
        }
      });
    },
    search() {
      // 搜索树
      if (this.searchKey) {
        // 模拟请求
        this.loading = true;
        this.postRequest("/gqQxCode/search",
            { title: this.searchKey ,
              version: '2023'}
        ).then(res => {
          this.loading = false;
          if (res.success) {
            res.result.forEach(function(e) {
              if (e.isParent) {
                e.loading = false;
                e.children = [];
                e._loading = false;
              }
            });
            this.data = res.result;
          }
        });
        // 模拟请求成功
        // this.data = [];
      } else {
        // 为空重新加载
        this.getParentList();
      }
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] === null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title
        this.form = data;
        this.form.title = data.title.substring(data.title.indexOf('-') + 1).trim();
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      this.form.id = "";
      this.editTitle = "";
    },
    selectTreeEdit(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] === null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        if (this.form.id == data.id) {
          this.$Message.warning("请勿选择自己作为父节点");
          v[0].selected = false;
          return;
        }
        this.form.parentId = data.id;
        this.form.parentTitle = data.title;
      }
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.form.status = 0;
    },
    // region TODO 右侧修改按钮
    submitEdit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.id) {
            this.$Message.warning("请先点击选择要修改的节点");
            return;
          }
          this.submitLoading = true;
          this.postRequest("/gqQxCode/edit", this.form).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("编辑成功");
              this.init();
              this.modalVisible = false;
            }
          });
        }
      });
    },
    // endregion

    // region TODO 添加子节点
    submitAdd() {
      this.$refs.formAdd.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.postRequest("/gqQxCode/add", this.formAdd).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("添加成功");
              this.init();
              this.modalVisible = false;
            }
          });
        }
      });
    },
    // endregion
    add() {

      if (this.form.id == "" || this.form.id == null) {
        this.$Message.warning("请先点击选择一个节点");
        return;
      }
      this.modalTitle = "添加子节点";
      this.showParent = true;
      if (!this.form.children) {
        this.form.children = [];
      }
      this.formAdd = {
        level: parseInt(this.form.level) + 1,
        parentTitle: this.form.title,
        parentCode: this.form.profCode,
        dictMatch: this.form.dictMatch,
        sortOrder: this.form.children.length + 1,
        version: '2023'
      };
      this.modalVisible = true;
    },
    addRoot() {
      this.modalTitle = "添加一级节点";
      this.showParent = false;
      this.formAdd = {
        parentCode: 0,
        dictMatch: this.gradNowDict,
        level: '0',
        sortOrder: this.data.length + 1,
        version: '2023'
      };
      this.modalVisible = true;
    },
    changeSelect(v) {
      this.selectList = v;
    },
    changeSelectLevel(v) {
      this.selectLevelList = v;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    tableAdd(v) {
      this.form = v;
      this.add();
      this.editTitle = "";
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
    },
    showSelect(e) {
      this.selectList = e;
    },
    remove(v) {
      this.selectList = [];
      this.selectList.push(v);
      this.delAll();
    },
    delAll() {
      if (this.selectList.length <= 0) {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的 " + this.selectList.length + " 条数据及其下级所有数据?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function (e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          this.postRequest("/gqQxCode/delByIds", {ids: ids}).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.selectList = [];
              this.cancelEdit();
              this.init();
            }
          });
        }
      });
    },
    //导入学院数据
    dropImportData() {
      this.importModalVisible = true;
    },
    beforeUploadImport(file) {
      this.uploadfile = file;
      const fileExt = file.name.split(".").pop().toLocaleLowerCase();
      if (fileExt == "xlsx" || fileExt == "xls") {
        this.readFile(file);
        this.file = file;
      } else {
        this.$Notice.warning({
          title: "文件类型错误",
          desc:
              "所选文件‘ " +
              file.name +
              " ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。",
        });
      }
      return false;
    },
    // 读取文件
    readFile(file) {
      this.reading = true;
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onerror = (e) => {
        this.reading = false;
        // this.$Message.error("文件读取出错");
        this.$Message.error({
          content:"文件读取出错",
          duration: 5,
          closable: true
        });
      };
      reader.onload = (e) => {
        const data = e.target.result;
        const {header, results} = excel.read(data, "array");
        const tableTitle = header.map((item) => {
          return {title: item, key: item, minWidth: 130, align: "center"};
        });
        this.importTableData = results;
        this.importColumns = tableTitle;
        this.reading = false;
        this.$Message.success("读取数据成功");
      };
    },
    clearImportData() {
      this.importTableData = [];
      this.importColumns = [];
      this.uploadfile = {};
    },
    downloadTemple() {
      // alert(process.env.BASE_URL + "专业代码导入模板.xlsx","process.env.BASE_URL + \"用户导入模板.xlsx\"")
      window.location.href = process.env.BASE_URL + "去向代码导入模板.xlsx";
    },
    importData() {
      let params = this.importTableData.map(item => {
        return {
          dictMatch: item['去向分类'],
          profCode: item['去向代码'],
          title: item['去向名称'],
          dlCode: item['去向大类代码'],
          dlTitle: item['去向大类'],
          zlCode: item['去向中类代码'],
          zlTitle: item['去向中类'],
          version: '2023'
        }
      });
      this.importLoading = true;
      this.postBodyRequest("/professionalCode/importData", params).then((res) => {
        this.importLoading = false;
        if (res.success) {
          this.importModalVisible = false;
          this.getParentList();
          this.$Modal.info({
            title: "导入结果",
            content: res.message,
          });
        }
      });
    },
    versDropdown(name){
      // if (name === "addVers"){
      //   this.currVersion = parseInt(this.versionList[0])+1
      //   const nextYear = new Date().getFullYear() + 1
      //   if (parseInt(this.currVersion) > nextYear){
      //     this.currVersion = nextYear
      //
      //   }
      //   this.$Message.warning("您只能添加" + (parseInt(this.currVersion)) + "年的去向代码版本！");
      // }else {
      //   this.currVersion = name
      // }
      // this.getParentList()
      // this.getAllDict()
    },
    async getVersionListInit(){
      this.postRequest("/professionalCode/getVersions").then((res) => {
        if (res.success){
          this.versionList = res.result
          // this.currVersion = this.versionList[0]
          // 获取树数据（字典）
          this.getAllDict();
        }
      })
    },
    onRestWindow() {
        this.columns = this.restTableCellWidth(this.columns_1)
        this.labelWidth110 = this.searchLabelWidth(this.labelWidth110)
        this.siderWidth = this.searchLabelWidth(this.siderWidth)
    }
  },
  mounted() {
    this.onRestWindow()
    window.addEventListener('resize',this.onRestWindow)
    this.init();
    this.height = Number(document.documentElement.clientHeight - 230);
  },
  beforeDestroy() {
    window.removeEventListener('resize',this.onRestWindow)
  },
  computed: {
    getLabelCode() {
      if (this.form.level === '0') {
        return '去向大类代码'
      } else if (this.form.level === '1') {
        return '去向中类代码'
      } else {
        return '去向代码'
      }
    },
    getLabelName() {
      if (this.form.level === '0') {
        return '去向大类名称'
      } else if (this.form.level === '1') {
        return '去向中类名称'
      } else {
        return '去向名称'
      }
    },
    getLabelChildCode() {
      if (this.form.level === '0') {
        return '去向中类代码'
      } else if (this.form.level === '1') {
        return '去向代码'
      } else {
        return '去向大类代码'
      }
    },
    getLabelChildName() {
      if (this.form.level === '0') {
        return '去向中类名称'
      } else if (this.form.level === '1') {
        return '去向名称'
      } else {
        return '去向大类名称'
      }
    },
  }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
// @import "../../../styles/tree-common.less";
// @import "../../../styles/drawer-common.less";
.search {
  .operation {
    margin-bottom: 2vh;
  }

  .select-title {
    font-weight: 600;
    color: #40a9ff;
  }

  .select-clear {
    margin-left: 10px;
  }
}

.tree-bar {
  overflow: auto;
  margin-top: 5px;
  position: relative;
  min-height: 80px;
}

.tree-select {
  max-height: 500px;
}

.tree-bar::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.tree-bar::-webkit-scrollbar-thumb {
  border-radius: 4px;
  -webkit-box-shadow: inset 0 0 2px #d1d1d1;
  background: #e4e4e4;
}

.drawer-footer {
  z-index: 10;
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  background: #fff;
}

.drawer-content {
  overflow: auto;
}

.drawer-content::-webkit-scrollbar {
  display: none;
}

.drawer-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
}

.drawer-title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  display: block;
  margin-bottom: 16px;
}
//.edit-head {
//  display: flex;
//  justify-content: space-between;
//  align-items: center;
//}
//.light-text {
//  color: #9ff8cf;
//  border: 1px solid #ccc;
//  padding: 5px;
//  border-radius: 4px;
//}

</style>
